﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PerlinNoiseImage : MonoBehaviour
{

        [Header("绘制宽度")]
        public int pictureWidth = 100;
        [Header("绘制高度")]
        public int pictrueHeight = 100;
        private float xoffest = .0f;
        private float yoffset = .0f;

        [Header("缩放大小")]
        public float noisescale = 1.0f;
        [Header("垂直速度")]
        public float scalespeed = 0.1f;
        [Header("水平速度")]
        public float scrollspeed = 1;
        [Header("颜色渐变")]
        public Gradient gradient;
        private Texture2D noiseTex;
        private Color[] pix;

        [Header("设置界面")]
        public GameObject isEnable;


        void Start()
        {
                noiseTex = new Texture2D(pictureWidth, pictrueHeight);
                this.GetComponent<Image>().material.SetTexture("_MainTex", noiseTex);
                pix = new Color[pictureWidth * pictrueHeight];
                xoffest = pictureWidth / 2;
                yoffset = pictureWidth / 2;
        }


        void Update()
        {
                if (isEnable.activeSelf)
                {
                        CalcNoise();
                        xoffest += Time.deltaTime * scrollspeed;
                        yoffset += Time.deltaTime * scrollspeed;
                }
        }

        private void CalcNoise()
        {
                float y = .0f;
                while (y < pictrueHeight)
                {
                        float x = .0f;
                        while (x < pictureWidth)
                        {
                                float xCoord = xoffest + x / pictureWidth * noisescale * (1 + Mathf.Sin(Time.time * scalespeed) * 0.1f);
                                float yCoord = yoffset + y / pictrueHeight * noisescale * (1 + Mathf.Cos(Time.time * scalespeed) * 0.1f);
                                Color color = gradient.Evaluate(Mathf.PerlinNoise(xCoord, yCoord));
                                pix[(int)(y * pictureWidth + x)] = color;
                                x++;
                        }
                        y++;
                }
                noiseTex.SetPixels(pix);
                noiseTex.Apply();
        }
}